from appium import webdriver
from selenium.webdriver.common.by import By
from appium.webdriver.extensions.android.nativekey import AndroidKey
from appium.options.android import UiAutomator2Options
import time
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

def setup_driver_bypass():
    """
    使用绕过方法初始化 Appium WebDriver
    Returns:
        WebDriver: 配置好的 WebDriver 实例
    """
    # 极简配置，绕过所有可能的权限检查
    desired_caps = {
        'platformName': 'Android',
        'deviceName': 'AMZXFYGYPNWG99X4',
        'appPackage': 'tv.danmaku.bili',
        'appActivity': '.MainActivityV2',
        'automationName': 'UiAutomator2',
        
        # 完全跳过所有初始化和设置步骤
        'skipDeviceInitialization': True,
        'skipServerInstallation': True,
        'skipLogcatCapture': True,
        'skipUnlock': True,
        'skipSystemBars': True,
        
        # 禁用所有可能触发权限检查的功能
        'ignoreHiddenApiPolicyError': True,
        'disableWindowAnimation': True,
        'enforceXPath1': True,
        
        # 超时设置
        'newCommandTimeout': 300,
        'uiautomator2ServerLaunchTimeout': 20000,
        'uiautomator2ServerInstallTimeout': 20000,
        'adbExecTimeout': 20000,
        
        # 设置参数（使用字符串格式）
        'settings': {
            'ignoreUnimportantViews': False,
            'allowInvisibleElements': True,
            'waitForIdleTimeout': 100,
            'waitForSelectorTimeout': 100,
            'normalizeTagNames': True,
            'shouldUseCompactResponses': False,
            'elementResponseAttributes': 'name,text,className,resourceId'
        }
    }
    
    try:
        logger.info("尝试连接到设备，使用绕过权限检查的配置...")
        driver = webdriver.Remote('http://localhost:4723/wd/hub', 
            options=UiAutomator2Options().load_capabilities(desired_caps))
        driver.implicitly_wait(5)
        logger.info("成功建立连接！")
        return driver
    except Exception as e:
        logger.error(f"绕过方法也失败了: {str(e)}")
        raise

def setup_driver_alternative():
    """
    替代方案：最小化配置
    """
    desired_caps = {
        'appium:platformName': 'Android',
        'appium:deviceName': 'AMZXFYGYPNWG99X4', 
        'appium:appPackage': 'tv.danmaku.bili',
        'appium:appActivity': '.MainActivityV2',
        'appium:automationName': 'UiAutomator2',
        'appium:noReset': True,
        'appium:newCommandTimeout': 0,
        'appium:forceEspressoRebuild': False
    }
    
    try:
        logger.info("尝试使用 W3C 格式的替代配置...")
        driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_capabilities=desired_caps)
        driver.implicitly_wait(5)
        logger.info("替代方案成功！")
        return driver
    except Exception as e:
        logger.error(f"替代方案失败: {str(e)}")
        raise

def handle_teen_protection(driver):
    """
    处理青少年保护弹窗
    Args:
        driver: WebDriver 实例
    """
    try:
        iknow = driver.find_elements(By.ID, "text3")
        if iknow:
            iknow[0].click()
            logger.info("已处理青少年保护弹窗")
    except Exception as e:
        logger.warning(f"处理青少年保护弹窗时出错: {str(e)}")

def search_videos(driver, keyword):
    """
    搜索视频
    Args:
        driver: WebDriver 实例
        keyword: 搜索关键词
    """
    try:
        # 点击搜索框
        driver.find_element(By.ID, 'expand_search').click()
        logger.info("已点击搜索框")
        
        # 输入搜索关键词
        sbox = driver.find_element(By.ID, 'search_src_text')
        sbox.send_keys(keyword)
        logger.info(f"已输入搜索关键词: {keyword}")
        
        # 按回车搜索
        driver.press_keycode(AndroidKey.ENTER)
        logger.info("已执行搜索")
        
        # 等待搜索结果加载
        time.sleep(3)
        
        # 获取搜索结果
        eles = driver.find_elements(By.ID, 'title')
        logger.info(f"找到 {len(eles)} 个搜索结果")
        
        for ele in eles:
            print(ele.text)
            
    except Exception as e:
        logger.error(f"搜索过程中出错: {str(e)}")
        raise

def main():
    """
    主函数
    """
    driver = None
    try:
        # 先尝试绕过方法
        try:
            driver = setup_driver_bypass()
        except:
            logger.info("绕过方法失败，尝试替代方案...")
            driver = setup_driver_alternative()
            
        handle_teen_protection(driver)
        search_videos(driver, "白月黑羽")
        input('**** 按回车键退出..')
    except Exception as e:
        logger.error(f"程序执行出错: {str(e)}")
        logger.info("所有方法都失败了。这可能是 Android 14 的兼容性问题。")
        logger.info("建议：1) 尝试在较低版本的 Android 设备上运行；2) 考虑使用其他自动化工具")
    finally:
        if driver:
            driver.quit()
            logger.info("已关闭 WebDriver")

if __name__ == "__main__":
    main()